{% extends "exam_system/base_exam.html" %}

{% block title %}{{ exam_room.name }}{% endblock %}

{% block content %}
<div class="container-fluid">
    {% if not can_start %}
        <div class="text-center mt-5">
            <h2>{{ exam_room.name }}</h2>
            {% if time_to_start > 0 %}
                <div class="alert alert-info">
                    <h4>考试即将开始</h4>
                    <p>距离考试开始还有 <span id="countdown">{{ time_to_start }}</span> 秒</p>
                    <p>试卷将在考试开始前自动生成，请耐心等待</p>
                </div>
            {% else %}
                <div class="alert alert-warning">
                    <h4>考试尚未开始</h4>
                    <p>请等待考试开始时间</p>
                </div>
            {% endif %}

            <div class="exam-info mt-4">
                <h4>考试信息</h4>
                <p>开始时间：{{ exam_room.start_time|date:"Y-m-d H:i" }}</p>
                <p>考试时长：{{ exam_room.duration }} 分钟</p>
                <p>总分：{{ exam_room.total_score }} 分</p>
                <p>题目数量：</p>
                <ul class="list-unstyled">
                    {% if exam_room.single_choice_count > 0 %}
                    <li>单选题：{{ exam_room.single_choice_count }}道（每题{{ exam_room.single_choice_score }}分）</li>
                    {% endif %}
                    {% if exam_room.multiple_choice_count > 0 %}
                    <li>多选题：{{ exam_room.multiple_choice_count }}道（每题{{ exam_room.multiple_choice_score }}分）</li>
                    {% endif %}
                    {% if exam_room.judgment_count > 0 %}
                    <li>判断题：{{ exam_room.judgment_count }}道（每题{{ exam_room.judgment_score }}分）</li>
                    {% endif %}
                </ul>
            </div>
        </div>
    {% else %}
        <div id="exam-start-section" class="text-center mt-5" {% if exam_started %}style="display:none;"{% endif %}>
            <h2>{{ exam_room.name }}</h2>
            <div class="alert alert-success">
                <h4>考试已开始</h4>
                <p>点击下方按钮开始答题</p>
                <button id="start-exam" class="btn btn-primary btn-lg mt-3">开始考试</button>
            </div>
        </div>

        <div id="exam-content" class="row" {% if not exam_started %}style="display:none;"{% endif %}>
            <!-- 左侧题目导航 -->
            <div class="col-md-2 p-0 border-end">
            <div class="question-nav">
                <div class="p-3 bg-light border-bottom">
                    <div class="timer text-center" data-end="{{ exam_room.end_time|date:'Y-m-d H:i:s' }}">
                        剩余时间：<span id="time-remaining"></span>
                    </div>
                </div>
                <div class="list-group list-group-flush">
                    {% regroup exam_paper.questions.all by question.question_type as question_groups %}
                    {% for group in question_groups %}
                        <div class="question-group">
                            <div class="list-group-item bg-light fw-bold align-center">
                                {% if group.grouper == 'single' %}
                                    单选题
                                {% elif group.grouper == 'multiple' %}
                                    多选题
                                {% elif group.grouper == 'judge' %}
                                    判断题
                                {% endif %}
                            </div>
                            {% for exam_question in group.list %}
                            <a href="#question-{{ exam_question.question_number }}"
                               class="list-group-item list-group-item-action {% if exam_question.answer %}answered{% endif %}"
                               data-bs-toggle="list">
                                第{{ exam_question.question_number }}题
                                {% if exam_question.answer %}
                                <i class="bi bi-check-circle-fill text-success float-end"></i>
                                {% endif %}
                            </a>
                            {% endfor %}
                        </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- 右侧答题区域 -->
        <div class="col-md-10">
            <div class="question-content">
                <div class="tab-content">
                    {% for exam_question in exam_paper.questions.all %}
                    <div class="tab-pane fade {% if forloop.first %}show active{% endif %}"
                         id="question-{{ exam_question.question_number }}">
                        <div class="question-header mb-4">
                            <h4>第{{ exam_question.question_number }}题
                                <small class="text-muted">
                                    ({{ exam_question.question.get_question_type_display }})
                                </small>
                            </h4>
                        </div>

                        <div class="question-body mb-4">
                            {{ exam_question.question.content|safe }}
                            {% if exam_question.question.image %}
                            <div class="question-image mt-3">
                                <img src="{{ exam_question.question.image.url }}"
                                     alt="题目图片"
                                     class="img-fluid">
                            </div>
                            {% endif %}
                        </div>

                        <div class="question-options">
                            <form class="answer-form"
                                  data-question-id="{{ exam_question.id }}"
                                  data-question-type="{{ exam_question.question.question_type }}">
                                {% if exam_question.question.question_type == 'judge' %}
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="answer" value="1"
                                           id="judge-true-{{ exam_question.id }}"
                                           {% if exam_question.answer == '1' %}checked{% endif %}>
                                    <label class="form-check-label" for="judge-true-{{ exam_question.id }}">
                                        正确
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="answer" value="0"
                                           id="judge-false-{{ exam_question.id }}"
                                           {% if exam_question.answer == '0' %}checked{% endif %}>
                                    <label class="form-check-label" for="judge-false-{{ exam_question.id }}">
                                        错误
                                    </label>
                                </div>
                                {% else %}
                                {% with options=exam_question.question.options.splitlines %}
                                {% for option in options %}
                                <div class="form-check">
                                    <input class="form-check-input"
                                           type="{% if exam_question.question.question_type == 'multiple' %}checkbox{% else %}radio{% endif %}"
                                           name="answer"
                                           value="{{ option | make_list | first }}"
                                           id="option-{{ exam_question.id }}-{{ forloop.counter }}"
                                           {% if exam_question.answer and forloop.counter0|stringformat:"s" in exam_question.answer %}checked{% endif %}>
                                    <label class="form-check-label" for="option-{{ exam_question.id }}-{{ forloop.counter0 }}">
                                        {{ option }}
                                    </label>
                                </div>
                                {% endfor %}
                                {% endwith %}
                                {% endif %}

                                <div class="mt-4">
                                    <button type="submit" class="btn btn-primary">提交答案</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>

    <!-- 底部状态栏 -->
    <div class="exam-status">
        <div class="container-fluid">
            <div class="row align-items-center">
                <div class="col">
                    已答题数：<span id="answered-count">0</span> / {{ exam_paper.questions.count }}
                </div>
                <div class="col text-end">
                    <button id="submit-exam" class="btn btn-danger">
                        提交试卷
                    </button>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
// 活动检测变量
let lastActivityTime = Date.now();
const INACTIVITY_LIMIT = 5 * 60 * 1000; // 5分钟无操作自动提交

// 防止页面后退
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

// 活动检测函数
function trackActivity() {
    lastActivityTime = Date.now();
}

// 初始化活动事件监听
['mousemove', 'keydown', 'click', 'scroll'].forEach(event => {
    document.addEventListener(event, trackActivity);
});

// 防止复制粘贴
document.addEventListener('copy', function(e) {
    e.preventDefault();
    alert('考试期间禁止复制');
});

document.addEventListener('paste', function(e) {
    e.preventDefault();
    alert('考试期间禁止粘贴');
});

// 页面离开提醒
window.onbeforeunload = function() {
    return "离开页面将视为交卷，确定要离开吗？";
};

$(document).ready(function() {
    // 更新剩余时间
    function updateTimeRemaining() {
        const endTime = new Date($('.timer').data('end'));
        const now = new Date();
        const diff = endTime - now;

        if (diff <= 0) {
            $('#time-remaining').html('<span class="text-danger">考试已结束</span>');
            submitExam();
            return;
        }

        const hours = Math.floor(diff / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((diff % (1000 * 60)) / 1000);

        $('#time-remaining').text(
            `${hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`
        );
    }

    // 更新已答题数
    function updateAnsweredCount() {
        const answeredCount = $('.list-group-item.answered').length;
        $('#answered-count').text(answeredCount);
    }

    // 提交答案
    $('.answer-form').on('submit', function(e) {
        e.preventDefault();
        const form = $(this);
        const questionId = form.data('question-id');
        const questionType = form.data('question-type');

        let answer;
        if (questionType === 'multiple') {
            answer = [];
            form.find('input[type="checkbox"]:checked').each(function () {
                answer.push($(this).val());
            });
            // 对多选题的答案进行排序，确保顺序一致性
            answer.sort();
            answer = answer.join(',');
        } else {
            answer = form.find('input[name="answer"]:checked').val();
        }

        $.ajax({
            url: '{% url "exam_system:submit_answer" %}',
            method: 'POST',
            data: {
                question_id: questionId,
                answer: answer,
                csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            success: function (response) {
                if (response.status === 'success') {
                    $(`a[href="#question-${response.question_number}"]`).addClass('answered').find('.float-end').remove();
                    $(`a[href="#question-${response.question_number}"]`).append('<i class="bi bi-check-circle-fill text-success float-end"></i>');
                    updateAnsweredCount();

                    // 自动跳转到下一题
                    const currentTab = $('.tab-pane.active');
                    const nextTab = currentTab.next('.tab-pane');
                    if (nextTab.length) {
                        $('.list-group-item').removeClass('active');
                        $(`a[href="#${nextTab.attr('id')}"]`).tab('show');
                    }
                } else {
                    alert('保存答案失败：' + response.message);
                }
            },
            error: function () {
                alert('网络错误，请重试');
            }
        });
    });

    // 开始考试
    $('#start-exam').on('click', function() {
        $('#exam-start-section').hide();
        $('#exam-content').show();
        updateTimeRemaining();
        setInterval(updateTimeRemaining, 1000);

        // 记录考试开始状态
        $.ajax({
            url: '{% url "exam_system:start_exam" exam_room.id %}',
            method: 'POST',
            data: {
                csrfmiddlewaretoken: '{{ csrf_token }}'
            },
            error: function() {
                console.error('无法记录考试开始状态');
            }
        });
    });

    // 提交试卷
    function submitExam() {
        if (!confirm('确定要提交试卷吗？提交后将无法修改答案。')) {
            return;
        }

        // 禁用页面离开提醒
        window.onbeforeunload = null;

        $.ajax({
            url: '{% url "exam_system:submit_exam" exam_paper.id %}',
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}'
            },
            data: {},
            success: function(response) {
                if (response.status === 'success') {
                    alert('试卷提交成功！');
                    window.location.href = response.redirect_url;
                } else {
                    alert('提交失败：' + response.message);
                }
            },
            error: function() {
                alert('网络错误，请重试');
            }
        });
    }

    $('#submit-exam').on('click', submitExam);

    // 倒计时功能（用于考试开始前）
    function updateCountdown() {
        const countdownElement = $('#countdown');
        if (countdownElement.length) {
            let timeLeft = parseInt(countdownElement.text());
            if (timeLeft > 0) {
                countdownElement.text(timeLeft - 1);
                setTimeout(updateCountdown, 1000);
            } else {
                location.reload();
            }
        }
    }

    // 定期自动保存（每30秒）
    function setupAutoSave() {
        setInterval(function() {
            $('.answer-form').each(function() {
                const form = $(this);
                const hasAnswer = form.find('input:checked').length > 0;
                if (hasAnswer && !form.data('saved')) {
                    form.submit();
                    form.data('saved', true);
                    setTimeout(function() {
                        form.data('saved', false);
                    }, 5000);
                }
            });
        }, 30000);
    }

    // 初始化
    if ($('#countdown').length) {
        updateCountdown();
    }

    if ($('#exam-content').is(':visible')) {
        updateTimeRemaining();
        setInterval(updateTimeRemaining, 1000);
        setupAutoSave();

        // 添加无操作自动提交检查
        setInterval(function() {
            const inactiveTime = Date.now() - lastActivityTime;
            if (inactiveTime > INACTIVITY_LIMIT) {
                alert('由于长时间无操作，系统将自动提交您的试卷');
                submitExam();
            } else if (inactiveTime > INACTIVITY_LIMIT - 60000) {
                // 提前1分钟警告
                const remainingSeconds = Math.ceil((INACTIVITY_LIMIT - inactiveTime) / 1000);
                if (remainingSeconds % 30 === 0) { // 每30秒提醒一次
                    alert(`您已${Math.floor(inactiveTime/60000)}分钟无操作，${remainingSeconds}秒后系统将自动提交试卷`);
                }
            }
        }, 30000); // 每30秒检查一次
    }

    updateAnsweredCount();

    // 题目导航点击事件
    $('.list-group-item').on('click', function(e) {
        e.preventDefault();
        // 获取目标tab的ID
        const targetId = $(this).attr('href');
        // 创建一个新的bootstrap.Tab对象并显示
        const tabToActivate = new bootstrap.Tab(this);
        tabToActivate.show();

        // 确保对应的tab-pane也被激活
        $('.tab-pane').removeClass('show active');
        $(targetId).addClass('show active');
    });
});
</script>
{% endblock %}
})